<template>
	<view class="container">

		<u-navbar bgColor="#0e3a5e" title="记录异常" :autoBack="true" :placeholder="true" leftIconColor="#fff"
			:titleStyle="data.titleStyle">
			<template #right>
				<view class="u-nav-slot">
					<u-icon name="plus-circle-fill" size="19" color="#fff" @click="openModal('add')"></u-icon>
				</view>
			</template>
		</u-navbar>
		<mescroll-body @init="mescrollInit" @down="downCallback" @up="upCallback" :up="upOption">
			<view class="pdBox" v-if="data.list.length">
				<view class="special_shake" v-for="(item,index) in data.list" :key="item.id">
					<view class="special_shake_item_top" v-if="item.status">
						<text style="font-size: 40rpx; font-weight: bold;">{{item.status}}</text>
						<u-icon name="trash" @click="delData(item, index)" v-if="item.status === '草稿'"></u-icon>
					</view>
					<view class="special_shake_item">
						<text class="special_shake_item_l">问题描述</text>
						<text class="special_shake_item_r">{{item.adjustItem}}</text>
					</view>
					<view class="special_shake_item">
						<text class="special_shake_item_l">反馈人</text>
						<text class="special_shake_item_r">{{item.operatorName}}</text>
					</view>
					<view class="special_shake_item">
						<text class="special_shake_item_l">反馈日期</text>
						<text class="special_shake_item_r">{{formatDate(item.operatorTime)}}</text>
					</view>
					<view class="special_shake_item">
						<view class="special_shake_item_l">
							<view class="">
								工艺判定
							</view>
							<view class="">
								品管判定
							</view>
						</view>
						<view class="special_shake_item_r attr">
							<view>
								<view class="">
									{{item.attr1}}
								</view>
								<view class="">
									{{item.attr2}}
								</view>
							</view>
						</view>
					</view>
					<view class="special_shake_item">
						<text class="special_shake_item_l">处理方案</text>
						<text class="special_shake_item_r">{{item.adjustResult}}</text>
					</view>
					<view class="special_shake_item borderNone">
						<text class="special_shake_item_l">图片</text>
						<view class="special_shake_item_r">
							<u-upload :fileList="item.keyfiles" @afterRead="afterRead" :name='`${item.id}`'
								:disabled="item.status !== '草稿' && item.status !== '已审核待处理'"
								@delete="deletePic($event,item)" multiple :previewFullImage="true"></u-upload>
						</view>
					</view>
					<u-button type="primary" text="提交" @click="submitCheckForm(item)"
						v-if="item.status === '草稿'" :throttleTime="1000"></u-button>
					<u-button type="primary" text="提交" @click="endCheck(item)"
						v-if="item.status === '已审核待处理'" :throttleTime="1000"></u-button>
				</view>
			</view>
		</mescroll-body>
		
		<u-modal :show="data.modalShow" :title="data.modalType === 'add'? '新增异常记录': data.modalType === 'check' ? '工艺判定': '处理方案'"
			:showCancelButton="true" @confirm="submitForm" @cancel="data.modalShow = false">
			<view class="slot-content">
				<u--form labelPosition="left" :model="data.form" ref="form1" label-width="80">
					<u-form-item label="反馈人" prop="sex" borderBottom @click="data.userPickerShow = true;">
						<u--input v-model="data.form.operatorName" disabled disabledColor="#ffffff" placeholder="请选择反馈人"
							border="none"></u--input>
						<template #right>
							<u-icon name="arrow-right"></u-icon>
						</template>
					</u-form-item>
					<u-form-item label="记录日期" prop="operatorDate" borderBottom @click="data.dateShow = true;">
						<u--input v-model="data.form.operatorDate" disabled disabledColor="#ffffff" placeholder="请选择记录日期"
							border="none"></u--input>
						<template #right>
							<u-icon name="arrow-right"></u-icon>
						</template>
					</u-form-item>
					<u-form-item label="异常描述" prop="adjustItem" borderBottom>
						<u--textarea v-model="data.form.adjustItem" placeholder="请输入异常描述" border="none"></u--textarea>
					</u-form-item>
				</u--form>
			</view>
		</u-modal>

		<u-picker :show="data.userPickerShow" keyName="nickName" :columns="data.userPickerColumns"
			@cancel="data.userPickerShow = false" @confirm="chooseUser"></u-picker>
		<u-datetime-picker :show="data.dateShow" v-model="data.form.time" mode="date" @cancel="data.dateShow = false"
			@confirm="chooseDate"></u-datetime-picker>
	</view>
</template>

<script lang="ts" setup>
	import {
		getAdjustItemList,
		getRoleUserList,
		adjusttypeitemSave,
		shakeDowndelete,
		itemFiledelete
	} from '@/api/planList/planList.js'
	import {
		reactive,
	} from "vue";
	import {
		onShow,
		onLoad,
		onReachBottom,
		onPageScroll
	} from "@dcloudio/uni-app";
	import useMescroll from "@/uni_modules/mescroll-uni/hooks/useMescroll.js";
	import dayjs from 'dayjs';
	import base from "@/common/baseUrl.js";
	const base_url = base.baseUrl

	const upOption = {
		noMoreSize: 10, //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看
		textNoMore: '-- 没有更多啦 --', // 没有更多数据的提示文本
		empty: {
			tip: '~ 暂无数据 ~' // 提示
		}
	}

	const { mescrollInit, downCallback, getMescroll } = useMescroll(onPageScroll, onReachBottom)
	const data = reactive({
		list: [],
		listQuery: {
			planEqmId: null,
			typeName: 'adjust_abnormal',
		},
		titleStyle: {
			color: '#fff',
			fontSize: '34rpx',
			fontWeight: '600'
		},
		modalShow: false,
		modalType: 'add',
		form: {
			time: Date.now()
		},
		userPickerShow: false,
		userPickerColumns: [],
		dateShow: false,
		checkModalShow: false
	})
	onLoad((option) => {
		if(option.planEqmId){
			data.listQuery.planEqmId = option.planEqmId
		}
		data.userInfo = uni.getStorageSync('userInfo')
		getRoleUserList({ roleNames: '生产' }).then(res => {
			data.userPickerColumns = [res.rows]
		})
	})
	onShow(() => {
	
	})
	const upCallback = async (mescroll) => {
		try{
			const params = {
				current: mescroll.num,
				size: mescroll.size,
				planEqmId: data.listQuery.planEqmId,
				typeName: data.listQuery.typeName,
			}
			const res = await getAdjustItemList(params)
			const curPageData = res.data.records || [] // 当前页数据
			if (mescroll.num == 1) data.list = []; // 第一页需手动制空列表
			data.list = data.list.concat(curPageData)
			data.list.map(item => {
				let keyfiles = []
				if (item.files && item.files.length) {
					item.files.map(i => {
						const keyfilesObj = {
							fileId: i.id,
							itemId: item.id,
							url: i.uri
						}
						keyfiles.push(keyfilesObj)
					})
			
				}
				item.keyfiles = keyfiles
				item.isExpand = false
				item.isBtnShow = false
			})
			mescroll.endByPage(curPageData.length, res.data.total);
		}catch(e){

			//TODO handle the exception
		}
	}


	const delData = async (item, index) => {
		uni.showModal({
			title: '提示',
			content: '确认删除吗？',
			success:async function (sres) {
				if (sres.confirm) {
					uni.showToast({
						title: '删除成功',
						icon:'none'
					})
					const res = await shakeDowndelete(item.id)
					getMescroll().resetUpScroll() 
				} 
			}
		});
	}
	const openModal = (type, row) => {
		data.modalType = 'add'
		data.form = {
			operator: data.userInfo.userId,
			operatorName: data.userInfo.nickName,
			operatorDate: dayjs().format('YYYY-MM-DD'),
			operatorTime: dayjs().unix()
		}
		data.modalShow = true
	}
	const openCheckModal = (row) => {
		data.modalType = 'check'
		data.form = { ...row }
		data.checkModalShow = true
	}
	const submitForm = () => {
		const { operatorDate, time, ...obj } = data.form
		obj.planEqmId = data.listQuery.planEqmId
		obj.typeName = 'adjust_abnormal'
		obj.status = '草稿'
		adjusttypeitemSave(obj).then(res => {
			if (res.status === 200) {
				uni.showToast({
					title: '操作成功',
					icon:'none'
				})
				data.modalShow = false
				getMescroll().resetUpScroll() 
			}
		})
	}
	const submitCheckForm = (row) => {
		data.form = { ...row }
		const { operatorDate, time, ...obj } = data.form
		obj.planEqmId = data.listQuery.planEqmId
		obj.typeName = 'adjust_abnormal'
		obj.status = '审核中'
		adjusttypeitemSave(obj).then(res => {
			if (res.status === 200) {
				uni.showToast({
					title: '操作成功',
					icon:'none'
				})
				data.checkModalShow = false
				getMescroll().resetUpScroll() 
			}
		})
	}
	const chooseUser = (e) => {
		if (data.modalType === 'add') {
			data.form.operator = e.value[0].userId
			data.form.operatorName = e.value[0].nickName
		} else {
			data.form.checker = e.value[0].userId
			data.form.checkerName = e.value[0].nickName
		}
		data.userPickerShow = false
	}
	const chooseDate = (e) => {
		data.form.operatorDate = dayjs(e.value).format('YYYY-MM-DD')
		data.form.operatorTime = e.value / 1000
		if (data.modalType === 'add') {
			data.form.operatorDate = dayjs(e.value).format('YYYY-MM-DD')
			data.form.operatorTime = e.value / 1000
		} else {
			data.form.checkerDate = dayjs(e.value).format('YYYY-MM-DD')
			data.form.checkerTime = e.value / 1000
		}
		data.dateShow = false
	}
	const afterRead = (e) => {
		const itemId = e.name;
		let files = e.file;
		if (files.length) {
			files.map(async (item) => {
				uni.uploadFile({
					url: base_url + '/proplan/plan/adjusttype/item/fileupload', //接口
					filePath: item.thumb,
					name: 'file',
					header: {
						Authorization: uni.getStorageSync("access_token"),
					},
					file: item,
					formData: {
						itemId
					},
					success: async res => {
						let resData = JSON.parse(res.data);
						if (resData.status == 200 && resData.data.uri) {
							data.list.map((i) => {
								if (i.id == itemId) {
									i.keyfiles.push({
										fileId: resData.data.id,
										itemId: itemId,
										url: resData.data.uri
									})
								}
							})
						}
					}
				})
			})
		}
	}
	const deletePic = (e, item) => {
		if (item.status !== '草稿' && item.status !== '已审核待处理') return
		uni.showModal({
			title: '提示',
			content: '确认要删除该条数据吗？',
			success: function (res) {
				if (res.confirm) {
					const index = data.list.findIndex(item => item.id == e.file.itemId)
					itemFiledelete(e.file.itemId, e.file.fileId).then(res => {
						data.list[index].keyfiles.splice(e.index, 1)
					})
				}
			}
		});

	}

	const formatDate = (val) => {
		return dayjs(val * 1000).format('YYYY-MM-DD');
	}
	const endCheck = (item) => {
		item.status = '待验收'
		adjusttypeitemSave(item).then(res => {
			if (res.status === 200) {
				uni.showToast({
					title: '操作成功',
					icon:'none'
				})
				data.checkModalShow = false
				getMescroll().resetUpScroll() 
			}
		})
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #f5f5f5;
	}
	.special_shake {
		background: #fff;
		margin-bottom: 40rpx;
		padding: 20rpx;
		border-radius: 10rpx;
		box-shadow: 0 0 10rpx 0 #bbbbbb;

		.special_shake_item_top {
			display: flex;
			justify-content: space-between;
			padding: 20rpx 0;
		}

		.special_shake_item {
			border-bottom: 1px solid #eeeeee;
			padding: 20rpx 0;
			font-size: 16px;
			display: flex;
			justify-content: space-between;
			align-items: flex-start;

			.special_shake_item_l {
				width: 30%;
			}

			.special_shake_item_r {
				flex: 1;
				color: #3975c6;

			}

			.attr {
				display: flex;
				justify-content: space-between;

				.u-button {
					width: 30px !important;
				}
			}
		}
	}
</style>